Advent of Code 2022 day 4
12/04/2025, 5:00 AMMarcin Wisniowski
12/04/2025, 5:08 AMMarcin Wisniowski
12/04/2025, 5:08 AMMarcin Wisniowski
12/04/2025, 5:08 AMtoGrid() and getAdjacent() at the ready helped a lot.Dan Fingal-Surma
12/04/2025, 5:15 AMMichael de Kaste
12/04/2025, 5:17 AMtoGrid() makes a Map<PairInt, Int, Char> of the input solution.
winds() returns its 8 neighbour pointsNorbert Kiesel
12/04/2025, 5:20 AMCharArea is similar to your Grid.
fun one(input: List<String>): Int {
val area = parse(input)
return area.tiles { it == '@' }.count { area.neighbors8(it, '@').size < 4 }
}Dan Fingal-Surma
12/04/2025, 5:28 AMMarcin Wisniowski
12/04/2025, 5:29 AMList<List<T>> and Map<Point, T>. 😄Dan Fingal-Surma
12/04/2025, 5:31 AMMap<Point, T> but part 1 was so easy with List<String> alone and I just extended the count function to remove optionallyJakub Gwóźdź
12/04/2025, 5:32 AMset<Pos> type:
fun List<CharSequence>.findAll(ch: Char): Set<Pos> = flatMapIndexed { r, line ->
line.mapIndexedNotNull { c, ch1 -> if (ch1 == ch) Pos(r, c) else null }
}.toSet()
fun part1(data: String): Any {
val rolls = data.lines().findAll('@')
return rolls.count(rolls::accessible)
}
fun part2(data: String): Any {
val rolls = data.lines().findAll('@').toMutableSet()
var result = 0
while (true) {
val removed = rolls.filter(rolls::accessible).toSet()
result += removed.size
rolls -= removed
if (removed.isEmpty()) break
}
return result
}
private fun Set<Pos>.accessible(pos: Pos): Boolean =
listOf(pos.n(), pos.e(), pos.s(), pos.w(), pos.ne(), pos.se(), pos.sw(), pos.nw()).count(this::contains) < 4Marcin Wisniowski
12/04/2025, 5:33 AMy9san9
12/04/2025, 5:34 AMbj0
12/04/2025, 5:34 AMMap, again with some recursionJakub Gwóźdź
12/04/2025, 5:36 AMThat also works nicely for boolean grids!Why only boolean? It actually works great for any kind of maps 🙂 And in bonus, I do not need to worry about going out of bounds.
Jakub Gwóźdź
12/04/2025, 5:37 AMchar separately)bj0
12/04/2025, 5:39 AMMichael de Kaste
12/04/2025, 5:39 AMvar current = parsed
while(true){
val step = current.step()
when(step){
current -> break
else -> current = step
}
}
and it ends up looking very clunky in my solution:
val current = generateSequence(parsed, Grid<Char>::step)
.zipWithNext()
.takeWhile { it.first != it.second }
.last().secondMichael Böiers
12/04/2025, 5:42 AMfun main() {
val grid = generateSequence(::readLine).flatMapIndexed { y, line ->
line.mapIndexedNotNull { x, char -> if (char == '@') x to y else null }
}.toMutableSet()
fun liftable() = grid.filter { (px, py) ->
(-1..1).flatMap { y -> (-1..1).map { px + it to py + y } }.count { it in grid } <= 4
}.toSet()
var lifted = 0
while (true) {
val liftable = liftable()
if (lifted == 0) println(liftable.size)
if (liftable.isEmpty()) break
grid -= liftable
lifted += liftable.size
}
println(lifted)
}Anirudh
12/04/2025, 5:43 AMThere are 2 types of people.I have both in Utils (I think) but I primarilyandList<List<T>>.Map<Point, T>
Map<Point, T> so it avoid most O(n) issues and free-null when a point isn't there.Michael Böiers
12/04/2025, 5:43 AMList<String>. That's my default, until something else is needed 🙂Anirudh
12/04/2025, 5:44 AMMichael Böiers
12/04/2025, 5:46 AMSetPair since that was all that was needed.Anirudh
12/04/2025, 5:49 AMMapPoint, T and during neighbour checks, I have a SetPoint for removedPoints which I check during the neighbour check.
reducing it just to a SetPoint would be much clenerbj0
12/04/2025, 5:50 AMMichael Böiers
12/04/2025, 5:51 AMy9san9
12/04/2025, 5:51 AMMichael de Kaste
12/04/2025, 5:53 AMy9san9
12/04/2025, 5:53 AM^ I'm kind of old school and solve AoC without any prepared code 🙂I am starting to think (after 5th aoc) that it's actually the right way. Because you learn how to write utility functions after many years much faster than it takes to understand them afterwards
Anirudh
12/04/2025, 5:53 AMmapper = { c: Char -> c }Michael Böiers
12/04/2025, 5:53 AMbj0
12/04/2025, 5:54 AMNeil Banman
12/04/2025, 6:00 AMprivate fun solve(loop: Boolean): Int {
val grid = input.toMutableGrid { c -> c == '@' }
var totalRemoved = 0
var removed = 0
do {
val removable = grid.withIndex()
.filter { (idx, b) ->
if (b) {
grid.getNeighbors(idx, true).count { it } < 4
} else {
false
}
}
for ((idx, _) in removable) {
grid[idx] = false
}
removed = removable.size
totalRemoved += removed
} while (loop && removed != 0)
return totalRemoved
}Norbert Kiesel
12/04/2025, 6:14 AMdo {
...
totalRemoved += removable.size
} while (loop && removable.isNotEmpty())Neil Banman
12/04/2025, 6:17 AMNeil Banman
12/04/2025, 6:20 AMwhile !foo.is_empty() ... when it's so much clearer to be able to say while (foo.isNotEmpty())y9san9
12/04/2025, 6:29 AMAnirudh
12/04/2025, 6:31 AM! at the beginning of a check. makes it hard to read whether it's being inverted or not. especially when using long expressions rather than just variablesNeil Banman
12/04/2025, 6:31 AMreally wish generateSequence has some build-in 'generate until difference' function.
fun <T> Sequence<T>.stabilized() = zipWithNext().first { (prev, next) -> prev == next }.first
fun <T> Sequence<IndexedValue<T>>.stabilized() = zipWithNext()
.first { (prev, next) -> prev.value == next.value }.firstAnirudh
12/04/2025, 6:32 AMfun partTwo(): Int {
val removeSeq = generateSequence(data.keys to 0) { (points, _) ->
val remove = points.filter { pt ->
pt.neighbours().count { it in points } < 4
}
points - remove.toSet() to remove.size
}
return removeSeq.drop(1).map { it.second }.takeWhile { it != 0 }.sum()
}
(PS. wish Slack would let us put the language after the three backticks. like StackOverflow ```kotlin )y9san9
12/04/2025, 6:33 AMNeil Banman
12/04/2025, 6:36 AMI'm kind of old school and solve AoC without any prepared code 🙂I'm not at all, but I really enjoy treating a String as a grid when I don't need to mutate anything. It's actually really ergonomic to navigate a String in 2D. The
\n s make it easy to do bounds checks and prevent rollovers from far right to far left.ephemient
12/04/2025, 6:43 AMreturn from an expression function is newephemient
12/04/2025, 6:51 AMEndre Deak
12/04/2025, 7:04 AM// from previous years, I have Coord implemented:
// data class Coord(val x: Int, val y: Int) : ComparableCoord
fun main() {
solve("Printing Department") {
val input = lines.toGrid { it } // MapCoord, Char
fun Map.EntryCoord, Char.removable() =
this.value == '@' && this.key.neighbours(true).count { c -> input[c] == '@'} < 4
part1 { input.count { it.removable() } }
part2 {
var sum = 0
while(true) {
input
.filter { it.removable() }
.takeIf { it.isNotEmpty() }
?.forEach { (c, _) -> input[c] = '.'; sum++ }
?: break
}
sum
}
}
}y9san9
12/04/2025, 7:10 AMMax Thiele
12/04/2025, 7:21 AMNeil Banman
12/04/2025, 7:23 AMMichael Böiers
12/04/2025, 7:25 AMpretty happy with the compactness todayYou're using a lot of hidden code though 🙂
y9san9
12/04/2025, 7:53 AMif (x.manhattan > y.manhattan)phldavies
12/04/2025, 7:55 AMMichael Böiers
12/04/2025, 8:20 AMfun main() = generateSequence(::readLine)
.flatMapIndexed { y, line -> line.mapIndexedNotNull { x, char -> if (char == '@') x to y else null } }
.toMutableSet().let { grid ->
generateSequence {
grid.filter { (px, py) ->
(-1..1).flatMap { y -> (-1..1).map { px + it to py + y } }.count { it in grid } <= 4
}.toSet().also { grid -= it }.size.takeIf { it > 0 }
}.toList().let {
println(it.first())
println(it.sum())
}
}Anirudh
12/04/2025, 8:36 AMreturn statements in expression bodies with explicit return types: whatsnew2220 link
it's in 2.2.20-dev-8187 (for 2.2.21). and also maybe you set language-version to 2.3?ephemient
12/04/2025, 8:41 AM-language-version. maybe it's a compiler bug that allows it in 2.2, not complaining, just surprisedephemient
12/04/2025, 8:47 AMKarloti
12/04/2025, 11:20 AMimport java.util.ArrayDeque
import kotlin.time.measureTimedValue
fun main() {
fun partOneAndTwo(lines: ListString): PairInt, Int {
data class Cell(var counts: Int, var isPaper: Boolean, var removed: Boolean)
data class Offset(val row: Int, val col: Int)
val (rows, cols) = lines.size to lines.first().length
val totalCells = rows * cols
val cells = List(totalCells) { Cell(counts = 0, isPaper = false, removed = false) }
val n4 = listOf(Offset(0, 1), Offset(1, -1), Offset(1, 0), Offset(1, 1))
val n8 = n4 + listOf(Offset(-1, -1), Offset(-1, 0), Offset(-1, 1), Offset(0, -1))
val queue = ArrayDequeInt()
for (i in cells.indices) {
val (r, c) = i / cols to i % cols
if (lines[r][c] == '@') {
cells[i].isPaper = true
n4.map { (dr, dc) -> Offset(dr + r, dc + c) }
.filter { (nr, nc) -> nr in 0..<rows && nc in 0..<cols && lines[nr][nc] == '@' }
.forEach { (nr, nc) -> cells[i].counts++; cells[nr * cols + nc].counts++ }
}
}
var part1Count = 0
cells.forEachIndexed { index, cell ->
if (cell.isPaper && cell.counts < 4) {
queue.add(index)
cell.removed = true
part1Count++
}
}
var part2Removed = part1Count
while (!queue.isEmpty()) {
val currentIdx = queue.poll()
val (r, c) = currentIdx / cols to currentIdx % cols
n8.map { (dr, dc) -> Offset(dr + r, dc + c) }
.filter { (nr, nc) -> nr in 0..<rows && nc in 0..<cols }
.map { (nr, nc) -> nr * cols + nc }
.filter { i -> cells[i].isPaper && !cells[i].removed }
.forEach { i ->
cells[i].counts--
if (cells[i].counts < 4) {
cells[i].removed = true
queue.add(i)
part2Removed++
}
}
}
return part1Count to part2Removed
}
val (p1Test, p2Test) = partOneAndTwo(readInput("Day04_test"))
check(p1Test == 13) { "Part 1 Test: $p1Test (Expected: 13)" }
check(p2Test == 43) { "Part 2 Test: $p2Test (Expected: 43)" }
val input = readInput("Day04")
val (result, time) = (1..10).map { measureTimedValue { partOneAndTwo(input) } }.minBy { it.duration }
println("Part 1: ${result.first}")
println("Part 2: ${result.second}")
println("Time: $time")
}
https://github.com/karloti/aoc-2025-in-kotlin/blob/main/src/Day04.ktJakub Gwóźdź
12/04/2025, 11:23 AMJakub Gwóźdź
12/04/2025, 11:26 AMKarloti
12/04/2025, 11:28 AMJakub Gwóźdź
12/04/2025, 11:29 AMJakub Gwóźdź
12/04/2025, 11:30 AMKarloti
12/04/2025, 11:43 AMephemient
12/04/2025, 11:53 AMJaap Beetstra
12/04/2025, 12:22 PMKarloti
12/04/2025, 12:43 PMKarloti
12/04/2025, 12:58 PMPaul Woitaschek
12/04/2025, 2:39 PMJakub Gwóźdź
12/04/2025, 2:58 PMEndre Deak
12/04/2025, 4:17 PMdata class Coord(val x: Int, val y: Int) : ComparableCoord {
override fun compareTo(other: Coord): Int = this.x.compareTo(other.x).takeIf { it != 0 } ?: this.y.compareTo(other.y)
}ephemient
12/04/2025, 4:57 PMoverride fun compareTo(other, coord): Int = compareValuesBy(this, other, Coord::x, Coord::y)phldavies
12/04/2025, 4:59 PMfinished warmup after 10.021194500s
year 2025 day 4 part 1
BitSet took 140.877us 👑: 1527
Default took 371.725us (2.64x): 1527
year 2025 day 4 part 2
BitSet took 498.471us 👑: 8690
Default took 10.900457ms (21.87x): 8690